import Vue from "vue";
import axios from "axios";
import router from "../route";
import { Dialog } from 'vant';

// 配置axios请求的baseURL
// axios.defaults.baseURL = '/api';
// axios.defaults.baseURL = '/abc';
axios.defaults.headers['Content-Type'];

// 配置响应拦截器
// axios.interceptors.response.use(
//   response => {
//     // 分析响应数据，处理响应拦截
//     return response.data
//   },
//   error => {
//     // 处理错误
//     return Promise.reject(error);
//   }
// );
// 基础地址
const baseUrl = "http://192.168.88.19:8080"
// 普通请求
const apiUrl = baseUrl + "/api"
// 图片地址
const imageUrl = baseUrl + "/res/image"

// 封装一般请求方法
const request = (url = "", options = {}) => {
  return new Promise((resolve, reject) => {
    options.method = options.method || "GET";
    options.data = options.data || {};
    options.params = options.params || {};
    options.headers = options.headers || {};

    axios.request({
      url: apiUrl + url,
      method: options.method,
      data: options.data,
      params: options.params,
      headers: options.headers
    })
    .then(response => {
      if (response.data.code === 90000004) {
        Dialog.alert({
          // title: '提示',
          message: '登录已过期，请重新登录！',
        }).then(() => {
          // on close
          localStorage.setItem("x-token", '')
          router.replace({path:'/mgr/login'})
        });
      }
      resolve(response.data);
    })
    .catch(error => {
      reject(error);
    });
  });
};

const api = {
  request,
  imageUrl
};

Vue.prototype.$api = api;

export default api;
